package com.example.myproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myproject.dto.exchange.ExchangeRequest;
import com.example.myproject.dto.exchange.ExchangeResponse;
import com.example.myproject.dto.exchange.TitleInfoDTO;
import com.example.myproject.mapper.TitleMapper;
import com.example.myproject.mapper.UserMoneyMapper;
import com.example.myproject.mapper.UserMapper;
import com.example.myproject.mapper.UserTitleMapper;
import com.example.myproject.model.Title;
import com.example.myproject.model.User;
import com.example.myproject.model.UserMoney;
import com.example.myproject.model.UserTitle;
import com.example.myproject.service.ExchangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExchangeServiceImpl implements ExchangeService {

    @Autowired
    private UserMoneyMapper userMoneyMapper;

    @Autowired
    private UserTitleMapper userTitleMapper;
    @Autowired
    private TitleMapper titleMapper; // 添加TitleMapper
    @Autowired
    private UserMapper userMapper;  // 添加 UserMapper 的注入
    private static final double TICKET_TO_MAGIC_RATE = 10.0; // 1点券=10魔力值
    private static final double TICKET_TO_POINT_RATE = 5.0; // 1点券=5积分
    private static final double MAGIC_TO_TITLE_COST = 50.0; // 兑换勋章需要50魔力值

    @Override
    @Transactional
    public ExchangeResponse exchangeTicketToMagic(Long userId, ExchangeRequest request) {
        UserMoney userMoney = userMoneyMapper.selectById(userId);
        if (userMoney == null || userMoney.getTicket() < request.getAmount()) {
            throw new RuntimeException("点券不足");
        }

        // 计算兑换后的魔力值
        double magicValue = request.getAmount() * TICKET_TO_MAGIC_RATE;

        // 更新用户点券和魔力值
        userMoney.setTicket(userMoney.getTicket() - request.getAmount());
        userMoney.setMagicvalue(userMoney.getMagicvalue() + magicValue);
        userMoneyMapper.updateById(userMoney);

        // 构建响应
        ExchangeResponse response = new ExchangeResponse();
        response.setMessage("兑换成功");
        response.setRemainingTicket(userMoney.getTicket());
        response.setRemainingMagicValue(userMoney.getMagicvalue());
        response.setRemainingPoint(userMoney.getPoint());
        // 设置gained
        ExchangeResponse.Gained gained = new ExchangeResponse.Gained();
        gained.setMagicValue(magicValue); // 你可以在Gained类中添加magicValue字段
        response.setGained(gained);
        return response;
    }

    @Override
    @Transactional
    public ExchangeResponse exchangeTicketToPoint(Long userId, ExchangeRequest request) {
        UserMoney userMoney = userMoneyMapper.selectById(userId);
        if (userMoney == null || userMoney.getTicket() < request.getAmount()) {
            throw new RuntimeException("点券不足");
        }

        // 计算兑换后的积分
        double points = request.getAmount() * TICKET_TO_POINT_RATE;

        // 更新用户点券和积分
        userMoney.setTicket(userMoney.getTicket() - request.getAmount());
        userMoney.setPoint(userMoney.getPoint() + points);
        userMoneyMapper.updateById(userMoney);

        // 构建响应
        ExchangeResponse response = new ExchangeResponse();
        response.setMessage("兑换成功");
        response.setRemainingMagicValue(userMoney.getMagicvalue());
        response.setRemainingTicket(userMoney.getTicket());
        response.setRemainingPoint(userMoney.getPoint());
        ExchangeResponse.Gained gained = new ExchangeResponse.Gained();
        gained.setPoint(points);
        response.setGained(gained);
        return response;



    }

    @Override
    @Transactional
    public ExchangeResponse exchangeMagicToTitle(Long userId, Long titleId) {
        // 检查勋章是否存在
        Title title = titleMapper.selectById(titleId);
        if (title == null) {
            throw new RuntimeException("勋章不存在");
        }

        UserMoney userMoney = userMoneyMapper.selectById(userId);
        if (userMoney == null || userMoney.getMagicvalue() < MAGIC_TO_TITLE_COST) {
            throw new RuntimeException("魔力值不足");
        }

        // 检查是否已拥有该勋章
        UserTitle existingTitle = userTitleMapper.selectOne(
                new QueryWrapper<UserTitle>()
                        .eq("user_id", userId)
                        .eq("title_id", titleId)
        );
        if (existingTitle != null) {
            throw new RuntimeException("已拥有该勋章");
        }

        // 扣除魔力值
        userMoney.setMagicvalue(userMoney.getMagicvalue() - MAGIC_TO_TITLE_COST);
        userMoneyMapper.updateById(userMoney);

        // 添加勋章
        UserTitle userTitle = new UserTitle();
        userTitle.setUserId(userId);
        userTitle.setTitleId(titleId);
        userTitleMapper.insert(userTitle);

        // 更新用户的当前勋章
        User user = userMapper.selectById(userId);
        user.setTitleId(titleId);
        userMapper.updateById(user);

        // 构建响应
        ExchangeResponse response = new ExchangeResponse();
        response.setMessage("兑换成功");
        response.setRemainingMagicValue(userMoney.getMagicvalue());
        response.setRemainingTicket(userMoney.getTicket());
        response.setRemainingPoint(userMoney.getPoint());
        ExchangeResponse.Gained gained = new ExchangeResponse.Gained();
        gained.setTitleId(titleId);
        response.setGained(gained);
        return response;
    }

    @Override
    public List<TitleInfoDTO> getUserTitles(Long userId) {
        // 查询用户拥有的所有勋章
        List<UserTitle> userTitles = userTitleMapper.selectList(
                new QueryWrapper<UserTitle>().eq("user_id", userId)
        );

        // 获取勋章详细信息
        return userTitles.stream()
                .map(userTitle -> {
                    Title title = titleMapper.selectById(userTitle.getTitleId());
                    TitleInfoDTO dto = new TitleInfoDTO();
                    dto.setTitleId(title.getTitleId());
                    dto.setTitleName(title.getTitleName());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<TitleInfoDTO> getAllAvailableTitles() {
        // 获取所有勋章
        List<Title> titles = titleMapper.selectList(null);

        // 转换为DTO
        return titles.stream()
                .map(title -> {
                    TitleInfoDTO dto = new TitleInfoDTO();
                    dto.setTitleId(title.getTitleId());
                    dto.setTitleName(title.getTitleName());
                    return dto;
                })
                .collect(Collectors.toList());
    }
    @Override
    @Transactional
    public ExchangeResponse rechargeTicket(Long userId, ExchangeRequest request) {
        if (request.getAmount() == null || request.getAmount() <= 0) {
            throw new RuntimeException("充值金额必须大于0");
        }
        UserMoney userMoney = userMoneyMapper.selectById(userId);
        if (userMoney == null) {
            // 如果没有记录，创建一条
            userMoney = new UserMoney();
            userMoney.setUserId(userId);
            userMoney.setTicket(request.getAmount());
            userMoney.setMagicvalue(0.0);
            userMoney.setPoint(0.0);
            userMoneyMapper.insert(userMoney);
        } else {
            userMoney.setTicket(userMoney.getTicket() + request.getAmount());
            userMoneyMapper.updateById(userMoney);
        }

        ExchangeResponse response = new ExchangeResponse();
        response.setMessage("充值成功");
        response.setRemainingTicket(userMoney.getTicket());
        response.setRemainingMagicValue(userMoney.getMagicvalue());
        response.setRemainingPoint(userMoney.getPoint());
        ExchangeResponse.Gained gained = new ExchangeResponse.Gained();
        gained.setPoint(0.0);
        gained.setMagicValue(0.0);
        response.setGained(gained);
        return response;
    }




}